package com.tlc.util;

import javax.servlet.http.Part;
import java.io.*;
import java.util.UUID;

public class UploadFiles {

    public String loadImage(Part part) {
        //获取提交的图片名
        String fileName = part.getSubmittedFileName();
        //如果目标文件夹不存在则创建
        File file = new File("E:/JAVA/image");

        if (!file.exists()) {
            file.mkdirs();
        }
        //随机生成图片名
        UUID uuid = UUID.randomUUID();
        String cover = uuid + fileName;
        //读取前端图片
        InputStream ios = null;
        //输出流
        OutputStream fos = null;
        try {
            ios = part.getInputStream();
            fos = new FileOutputStream(file + "/" + cover);
            int len = -1;
            while ((len = ios.read()) != -1) {
                fos.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ios != null) {
                try {
                    ios.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return cover;
    }
}
